<template>
    <div>
        <el-form :model="addForm" ref="addFormRef" :rules="rules" status-icon style="width: 300px;">
            <el-form-item label="藏品名称" prop="shopName">
                <el-input v-model="addForm.shopName" />
            </el-form-item>
            <el-form-item label="藏品价格" prop="shopPrice" :rules="[
                { required: true, message: '请输入藏品价格' },
                { type: 'number', message: '请输入数字值' },
            ]">
                <el-input v-model.number="addForm.shopPrice" />
            </el-form-item>
            <el-form-item label="图片" prop="shopImg">
                <el-upload action="#" :limit="1" list-type="picture-card" :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove" :on-exceed="handleExceed" :before-upload="handleUpload"
                    :http-request="uploadAction">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="add(addFormRef)">添加商品</el-button>
            </el-form-item>
        </el-form>
        <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { UploadProps, UploadRequestOptions, UploadRawFile, FormInstance } from 'element-plus'
import { addShopList } from "../../api/api";
import { useRouter } from 'vue-router';

const addForm = reactive({
    shopName: '',
    shopPrice: '',
    shopImg: '',
})

const rules = reactive<FormRules>({
    shopName: [
        { required: true, message: '请输入藏品名称', trigger: 'blur' }
    ]
})

const dialogImageUrl = ref<string | undefined>('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
}

const handleExceed: UploadProps['onExceed'] = (files) => {
    ElMessage.warning(
        `允许上传图片的最大数量为 ${files.length} 张`
    )
}

const handleUpload = (rawFile: UploadRawFile) => {
    const type = ['image/jpeg', 'image/jpg', 'image/png']
    if (type.indexOf(rawFile.type) === -1) {
        ElMessage.error('上传的文件必须是JPG、JPEG、PNG三种之一!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
    }
    return true
}

const uploadAction = (data: UploadRequestOptions) => {
    let reader = new FileReader() // 创建文件读取对象
    let file = data.file
    reader.readAsDataURL(file) // 文件读取转换为base64类型
    reader.onloadend = function (e: any | null) {
        // console.log(e.target.result);
        addForm.shopImg = e.target.result
    }
    let param = new FormData();
    param.append('file', data.file);
}

const addFormRef = ref<FormInstance>()

const router = useRouter()
const add = (ruleForm: FormInstance | undefined) => {
    if (!ruleForm) return
    ruleForm.validate(async (valid: any, fields: any) => {
        let data = {
            shopImg: addForm.shopImg,
            shopName: addForm.shopName,
            shopPrice: addForm.shopPrice
        }
        if (valid) {
            // 发送请求
            console.log('submit!')
            await addShopList(data)
            router.push('/productlist')
        } else {
            console.log('error submit!', fields)
            return false
        }
    })
}
</script>

<style scoped>

</style>